<template>
  <div class="setting-container">
    <div class="app-container">
      <!-- 卡片组件 -->
      <el-card class="box-card">
        <!-- 使用 Tabs 组件完成标签页布局 -->
        <el-tabs v-model="activeName" v-loading="loading">
          <el-tab-pane label="角色管理" name="first" class="tab-pane">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button icon="el-icon-plus" size="small" type="primary" @click="addRoleDialog">
                新增角色
              </el-button>
            </el-row>
            <!-- 使用 Table 组件实现用户角色的渲染 -->
            <el-table :data="rolesList" border style="width: 100%">
              <el-table-column type="index" label="序号" width="120" />
              <el-table-column prop="name" label="角色名" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="setRoles(scope.row)">
                    分配权限
                  </el-button>
                  <el-button size="small" type="primary" @click="editRoles(scope.row)">
                    编辑
                  </el-button>
                  <el-button size="small" type="danger" @click="delRoles(scope.row, scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination
              :current-page="query.page"
              :page-sizes="[5, 10, 15, 20, 25]"
              :page-size="query.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" class="tab-pane">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyInfo.name" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyInfo.companyAddress" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyInfo.mailbox" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyInfo.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑角色' : '新增角色'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="closeDialog"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="roleRules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>

        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="cancleRoles">取消</el-button>
            <el-button size="small" type="primary" @click="roleSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <!-- 分配权限弹框 -->
      <el-dialog title="分配权限点" :visible.sync="permissionDialog" @close="closePerDia">
        <!-- v-model语法糖
        :value='permissionDialog'
        @input= value => permissionDialog = value
         -->
        <assign-permission
          v-model="permissionDialog"
          :role-id="roleId"
          :permission-list="permissionList"
          :permission-id-list="permissionIDs"
          @setRolesEv="setRolesFn"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getRoleListAPI,
  getCompanyInfoAPI,
  addRoleAPI,
  delRoleAPI,
  editRoleAPI,
  getRoleDetailAPI,
  getPermissionListAPI,
  assignPremAPI
} from '@/api'
import assignPermission from './components/assignPermission.vue'
import { transTree } from '@/utils'
export default {
  components: { assignPermission },
  data() {
    return {
      activeName: 'first',
      query: {
        page: 1, // 当前页面
        pagesize: 5 // 页面显示的条数
      },
      rolesList: [], // 角色列表
      total: 0, // 角色数据总条数
      companyInfo: {}, // 公司信息
      // ...其他选项
      showDialog: false, // 控制弹框的隐藏和展示
      // 添加角色
      roleForm: {
        name: '',
        description: ''
      },
      // 添加角色验证
      roleRules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      // 是否编辑角色
      isEdit: false,
      // 编辑角色的id
      editRoleID: '',
      permissionDialog: false,
      loading: true,
      permissionList: [],
      permissionIDs: [],
      roleId: ''
    }
  },
  created() {
    // 获取员工列表
    this.getRoleList()
    // 获取公司信息
    this.getCompanyInfo()
  },
  methods: {
    // 每页显示的条数发生改变时触发
    handleSizeChange(size) {
      this.query.pagesize = size
      this.getRoleList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(pager) {
      this.query.page = pager
      this.getRoleList()
    },

    // 设置角色
    async setRoles(row) {
      this.permissionDialog = true
      // 获取权限列表
      await this.getPermissionList()
      // 获取角色详情
      await this.getRoleDetail(row.id)
      this.roleId = row.id
    },

    // 显示编辑角色弹窗
    async editRoles(row) {
      this.editRoleID = row.id
      this.isEdit = true
      this.showDialog = true
      // 数据回显,在 form 表单 mounted之后再进行赋值操作,防止表单初始值不为空
      this.$nextTick(() => {
        this.getRoleDetail(row.id)
      })
    },

    // 删除角色
    async delRoles(row, index) {
      try {
        if (this.rolesList.length === 1 && this.query.page > 1) {
          await delRoleAPI(row.id)
          this.rolesList.splice(index, 1)
          this.query.page--
        } else {
          await delRoleAPI(row.id)
          this.rolesList.splice(index, 1)
        }
        // 刷新页面
        this.getRoleList()
      } catch (err) {
        console.log(err)
      }
    },

    // 获取角色详情
    async getRoleDetail(id) {
      const res = await getRoleDetailAPI(id)
      this.roleForm = res.data
      this.permissionIDs = res.data.permIds
    },

    // 获取员工列表
    async getRoleList() {
      const res = await getRoleListAPI(this.query)
      console.log(res)
      this.rolesList = res.data.rows
      this.total = res.data.total
      this.loading = false
    },

    // 获取公司信息
    async getCompanyInfo() {
      const res = await getCompanyInfoAPI(this.$store.getters.companyId)
      console.log(res)
      this.companyInfo = res.data
    },

    // 显示新增角色弹框
    addRoleDialog() {
      this.isEdit = false
      this.showDialog = true
    },

    // 新增角色
    async addRole() {
      const res = await addRoleAPI(this.roleForm)
      console.log(res)
    },

    // 确定按钮
    roleSubmit() {
      // eslint-disable-next-line
      this.$refs.roleForm.validate(async (valid) => {
        if (valid) {
          if (!this.isEdit) {
            await this.addRole()
            // 刷新页面
            await this.getRoleList()
          } else {
            await editRoleAPI(this.editRoleID, this.roleForm)
            // 刷新页面
            await this.getRoleList()
          }
          this.showDialog = false
          // this.$refs.roleForm.resetFields()
        }
      })
    },

    // 取消按钮
    cancleRoles() {
      this.showDialog = false
    },
    // 关闭弹窗
    closeDialog() {
      // 重置表单
      this.$refs.roleForm.resetFields()
    },

    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionListAPI()
      console.log(res)
      this.permissionList = transTree(res.data, '0')
    },

    // 关闭权限弹窗
    closePerDia() {
      this.permissionIDs = []
    },

    //
    async setRolesFn(val) {
      await assignPremAPI(val)
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  padding: 10px 30px;
}

.tab-pane {
  padding: 20px;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style>
